$(document).ready(function() {
    var critModelJson = $(".criteria").parent().data("data")
    if (critModelJson) {
        var critModel = jQuery.parseJSON(critModelJson);
    }
    
    var criteria = $(".criteria").dataTable({
        "bScrollCollapse": true,
        "bFilter": false,
        "bSort": false,
        "bInfo": false,
        "bLengthChange": false,
        "bPaginate": false,
        "bJQueryUI": true,
        "aoColumnDefs": [
        {
            "aTargets": [ 0 ],
            "bSortable": false,
            "sClass": "field"
        },
        {
            "aTargets": [ 1 ],
            "bSortable": false,
            "sClass": "op"
        },
        {
            "aTargets": [ 2 ],
            "bSortable": false,
            "sClass": "value"
        }
        ],
        "aaData": critModel,
        "oLanguage": {
            "sEmptyTable": "Empty"
        },

        "eof": true
    });
    $(".criteria tbody").click(function(event) {
        $(criteria.fnSettings().aoData).each(function (){
            $(this.nTr).removeClass("row_selected");
        });
        $(event.target.parentNode).addClass("row_selected");
    });
    $(".criteria-delete").click(function() {
        function fnGetSelected(oTableLocal) {
            var aReturn = new Array();
            var aTrs = oTableLocal.fnGetNodes();

            for (var i=0; i<aTrs.length; i++) {
                if ($(aTrs[i]).hasClass("row_selected")) {
                    aReturn.push( aTrs[i]);
                }
            }
            return aReturn;
        }
        var anSelected = fnGetSelected(criteria);
        if (anSelected.length > 0) {
            criteria.fnDeleteRow( anSelected[0]);
        } else {
            alert('The criterion to be deleted is not selected')
        }
    })
    $(".criteria-add").click(function() {
        var field = $(".filter-parameters .field").val();
        var op = $(".filter-parameters .op").val();
        var value = $(".filter-parameters .value").val();

        var ev = value.replace('<', '&lt;')
            .replace('>', '&gt;')
            .replace('"', '&quot;');

        op = op.replace('<', '&lt;')
            .replace('>', '&gt;')
            .replace('"', '&quot;');

        var settings = criteria.fnSettings();
        var key = settings.iNextId;

        function render(name, type, key, value) {
            var html = '<input type="' + type + '" name="' + name + '[' + key + ']" value="' +
                value + '" id="criteria_' + name + key + '"/>';
            return html;
        }
        var fieldHtml = render('field', 'hidden', key, field) + field;
        var opHtml = render('op', 'hidden', key, op) + op;
        var valueHtml = render('value', 'hidden', key, '') + ev;

        criteria.fnAddData([fieldHtml, opHtml, valueHtml]);

        $('#criteria_value' + key).val(value);
    });

});